<template>
  <!-- 组织架构表单 -->
  <el-dialog :visible.sync="localVisible" :title="title" width="630px" :before-close="handleClose">
    <el-transfer v-model="value" :data="data" :titles="titles"></el-transfer>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleAdd">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import { getUserRole, delUserRole, addUserRole } from '@/api/user';
export default {
  name: 'userRole',
  components: {
    ImageUpload
  },

  props: {
    showRoleDialog: {
      type: Boolean,
      default: false,
      required: true
    },
    title: {
      type: String,
      default: '新增角色'
    },
    userId: {
      type: Number,
      default: null,
    }
  },
  data() {
    return {
      localVisible: this.showRoleDialog,
      data: [
        { key: 1, label: '系统管理员', disabled: false },
        { key: 2, label: '校长', disabled: false },
        { key: 3, label: '财务', disabled: false },
        { key: 4, label: '教务主任', disabled: false },
        { key: 5, label: '教务', disabled: false }
      ],
      // 当前已分配的权限id
      value: [],
      // 用户原始的权限 ID
      originalValue: [],
      titles: [
        '未分配角色',
        '已分配角色'
      ]


    };
  },
  watch: {
    // 监听父组件传递的 visible，同步到本地变量
    showRoleDialog(newVal) {
      this.localVisible = newVal;
    },
    // 监听本地变量的变化，通知父组件更新 visible
    localVisible(newVal) {
      if (newVal !== this.showRoleDialog) {
        this.$emit('update:showRoleDialog', newVal);
      }
    }
  },
  methods: {
    handleClose() {

      this.localVisible = false; // 修改本地变量
    },

    // 处理用户权限新增删除
    async handleAdd() {

      const addedRoles = this.value.filter(id => !this.originalValue.includes(id)); // 新增的权限
      const removedRoles = this.originalValue.filter(id => !this.value.includes(id)); // 移除的权限
      console.log('新增权限:', addedRoles);
      console.log('移除权限:', removedRoles);
      if (addedRoles.length > 0) {
        await addUserRole({ userId: this.userId, roleId: addedRoles.join(',') }); // 调用新增权限接口
      }
      if (removedRoles.length > 0) {
        await delUserRole({ userId: this.userId, roleId: removedRoles.join(',') }); // 调用移除权限接口
      }
      // 通知父组件更新
      this.$emit('submit')
      //成功提示
      this.$message.success('更新成功')
      this.localVisible = false; // 修改本地变量

    },

    async getUserRole() {
      const result = await getUserRole({ id: this.userId })
      this.value = result.map(item => item.id);
      console.log(this.value);

      this.originalValue = [...this.value]; // 保存原始权限

    }

  }
};
</script>

<style scoped>
/* 可以在这里添加样式 */
</style>